package com.android.chat.example;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.android.chat.connection.ServerConnect;

public class LoginActivity extends Activity {
	public static final String KEY_USERNAME = "Username";
	public static final String KEY_PASSWORD = "Password";

	EditText txtUsername;
	EditText txtPassword;

	LinearLayout load;
	Handler h = new Handler();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		txtUsername = (EditText) findViewById(R.id.txtUsername);
		txtPassword = (EditText) findViewById(R.id.txtPassword);
		
		// set de login nhanh check nhung cai khac
		txtUsername.setText("huunc91");
		txtPassword.setText("1234567");

		load = (LinearLayout) findViewById(R.id.load);

		Button btnLogin = (Button) findViewById(R.id.btnLogin);

		btnLogin.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				login(txtUsername.getText().toString(), txtPassword.getText()
						.toString());
			}
		});

		if (savedInstanceState != null) {
			txtUsername.setText(savedInstanceState
					.getString(LoginActivity.KEY_USERNAME));
			txtPassword.setText(savedInstanceState
					.getString(LoginActivity.KEY_PASSWORD));
		}
	}

	private void login(final String username, final String password) {
		// Intent intent = new Intent(this, SampleChatActivity.class);
		// intent.putExtra(KEY_USERNAME, txtUsername.getText().toString());
		// intent.putExtra(KEY_PASSWORD, txtPassword.getText().toString());

		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				h.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						load.setVisibility(View.VISIBLE);
					}
				});

				if (ServerConnect.authenticate(username, password)) {
					startActivity(new Intent(getApplicationContext(),
							SampleChatActivity.class));
				} else {
					
				}

				h.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						load.setVisibility(View.GONE);
					}
				});
			}
		});
		t.start();

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		saveState();
		outState.putSerializable(LoginActivity.KEY_USERNAME, txtUsername
				.getText().toString());
		outState.putSerializable(LoginActivity.KEY_PASSWORD, txtPassword
				.getText().toString());
	}

	@Override
	protected void onPause() {
		super.onPause();
		saveState();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private void saveState() {

	}
}
